package com.sai.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sai.common.result.Result;
import com.sai.system.entity.SysUser;
import com.sai.system.entity.SysUserRole;
import com.sai.system.model.DepartIdModel;
import com.sai.system.service.ISysUserDepartService;
import com.sai.system.service.ISysUserRoleService;
import com.sai.system.service.ISysUserService;
import com.sai.system.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户表 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @GetMapping(value = "/getCurrentUserInfo")
    public Result getCurrentUserInfo(HttpServletRequest req) {
        return Result.success(sysUserService.getCurrentUserInfo());
    }

    /**
     * 查询当前用户的所有部门/当前部门编码
     *
     * @return
     */
    @GetMapping(value = "/getCurrentUserDeparts")
    public Result getCurrentUserDeparts() {
        return Result.success(sysUserService.getCurrentUserDeparts());
    }

    /**
     * 登陆成功选择用户当前部门
     *
     * @param param
     * @return
     */
    @PutMapping(value = "/selectDepart")
    public Result selectDepart(@RequestBody Map<String, String> param) {
        return Result.success(sysUserService.updateCurrentUserDepart(param.get("orgCode")));
    }

    @GetMapping(value = "/list")
    public Result queryPageList(SysUser user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        return Result.success(sysUserService.pageUser(user, pageNo, pageSize, req.getParameterMap()));
    }

    @PostMapping(value = "/add")
    @RequiresPermissions("user:add")
    public Result<SysUser> add(@RequestBody JSONObject jsonObject) {
        String selectedRoles = jsonObject.getString("selectedroles");
        String selectedDeparts = jsonObject.getString("selecteddeparts");
        SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
        return Result.success(sysUserService.addUser(user, selectedRoles, selectedDeparts));
    }

    @GetMapping(value = "/queryUserRole")
    public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
        if (userRole == null || userRole.size() <= 0) {
            return Result.error("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleId());
            }
            return Result.success(list);
        }
    }

    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/userDepartList")
    public Result<Object> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        try {
            List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
            return Result.success(depIdModelList);
        } catch (Exception e) {
            return Result.error("查找过程中出现了异常: " + e.getMessage());
        }

    }

    @PutMapping(value = "/edit")
    @RequiresPermissions("user:edit")
    public Result<SysUser> edit(@RequestBody JSONObject jsonObject) {
        String roles = jsonObject.getString("selectedroles");
        String departs = jsonObject.getString("selecteddeparts");
        SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
        return Result.success(sysUserService.editUser(user, roles, departs));
    }

    @GetMapping(value = "/export")
    public Result export(SysUser user, HttpServletRequest req) {
        List<SysUser> list = sysUserService.list(user, req.getParameterMap());
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

}
